<template>
	<div class="leave-apply-container">
		<el-card class="leave-apply-card">
			<h2 class="form-title">请假申请</h2>
			<el-form
				:model="leaveForm"
				:rules="rules"
				ref="formRef"
				label-width="100px"
				class="leave-form"
			>
				<el-form-item label="请假类型" prop="leaveType">
					<el-select v-model="leaveForm.leaveType" placeholder="请选择">
						<el-option label="事假" value="personal"></el-option>
						<el-option label="病假" value="sick"></el-option>
						<el-option label="年假" value="annual"></el-option>
						<el-option label="调休" value="compensatory"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="开始日期" prop="startTime">
					<el-date-picker
						v-model="leaveForm.startTime"
						type="date"
						placeholder="选择开始日期"
						style="width: 100%"
					/>
				</el-form-item>

				<el-form-item label="结束日期" prop="endTime">
					<el-date-picker
						v-model="leaveForm.endTime"
						type="date"
						placeholder="选择结束日期"
						style="width: 100%"
					/>
				</el-form-item>

				<el-form-item label="请假天数" prop="leaveDays">
					<el-input v-model="leaveForm.leaveDays" :disabled="true" />
				</el-form-item>

				<el-form-item label="请假原因" prop="reason">
					<el-input
						type="textarea"
						v-model="leaveForm.reason"
						placeholder="请填写请假原因"
						:rows="4"
					/>
				</el-form-item>

				<el-form-item label="审批人ID（可选）" prop="approverId">
					<el-input v-model="leaveForm.approverId" placeholder="填写审批人ID" />
				</el-form-item>

				<div class="form-actions">
					<el-button type="primary" @click="submitLeave" :loading="submitLoading">
						提交申请
					</el-button>
					<el-button @click="resetForm">重置</el-button>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup>
import { ref, watch } from "vue";
import axios from "@/utils/axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useAuthStore } from "@/stores/auth";

// 表单引用与状态
const formRef = ref(null);
const submitLoading = ref(false);
const leaveForm = ref({
	leaveType: "",
	startTime: null,
	endTime: null,
	leaveDays: 0,
	reason: "",
	approverId: null,
});

const rules = ref({
	leaveType: [{ required: true, message: "请选择请假类型", trigger: "change" }],
	startTime: [{ required: true, message: "请选择开始日期", trigger: "change" }],
	endTime: [{ required: true, message: "请选择结束日期", trigger: "change" }],
	reason: [{ required: true, message: "请填写请假原因", trigger: "blur" }],
});

// 计算请假天数（含首尾）
const computeDays = () => {
	const s = leaveForm.value.startTime;
	const e = leaveForm.value.endTime;
	if (!s || !e) return 0;
	const sd = new Date(s).setHours(0,0,0,0);
	const ed = new Date(e).setHours(0,0,0,0);
	const msPerDay = 24 * 60 * 60 * 1000;
	const diff = Math.round((ed - sd) / msPerDay) + 1;
	return diff > 0 ? diff : 0;
};

watch(
	() => [leaveForm.value.startTime, leaveForm.value.endTime],
	() => {
		leaveForm.value.leaveDays = computeDays();
	}
);

// 提交逻辑
const submitLeave = async () => {
	const valid = await formRef.value.validate().catch(() => false);
	if (!valid) {
		ElMessage.warning("请填写完整并正确的信息！");
		return;
	}

	if (leaveForm.value.leaveDays <= 0) {
		ElMessage.warning("结束日期须在开始日期之后或与开始日期相同");
		return;
	}

	submitLoading.value = true;
	try {
		// 获取当前 loginId（优先从 store，然后回退到 localStorage）
		const auth = useAuthStore();
		const loginId = auth.currentLoginId || localStorage.getItem("currentLoginId") || localStorage.getItem("loginId");

		if (!loginId) {
			ElMessage.error("未获取到登录信息，请重新登录");
			return;
		}

		// 通过 loginId 查询 empId（兼容多种返回格式）
		const empRes = await axios.get("/user/getEmpId", { params: { loginId } });
		// empRes 可能是完整响应或直接数据，尝试解析
		let empId = null;
		if (empRes && empRes.data) {
			if (typeof empRes.data === "object" && empRes.data.data != null) {
				// 常见结构 { code: 200, data: X }
				empId = empRes.data.data;
				// 如果 data 是对象并含 empId 字段
				if (empId && typeof empId === "object" && empId.empId != null) {
					empId = empId.empId;
				}
			} else {
				// 纯数据返回
				empId = empRes.data;
			}
		} else if (typeof empRes === "number" || typeof empRes === "string") {
			empId = empRes;
		}

		console.log("查询 empId 返回：", empRes, "解析 empId：", empId);

		if (!empId) {
			ElMessage.error("未找到对应员工信息");
			return;
		}

		// 映射请假类型到数字（示例映射，可按后端要求调整）
		const typeMap = { personal: 1, sick: 2, annual: 3, compensatory: 4 };
		const leaveTypeNum = typeMap[leaveForm.value.leaveType] || 1;

		const submitData = {
			applyId: 0,
			empId: Number(empId),
			approverId: leaveForm.value.approverId ? Number(leaveForm.value.approverId) : 0,
			leaveType: leaveTypeNum,
			startTime: leaveForm.value.startTime ? new Date(leaveForm.value.startTime).toISOString() : "",
			endTime: leaveForm.value.endTime ? new Date(leaveForm.value.endTime).toISOString() : "",
			leaveDays: leaveForm.value.leaveDays,
			reason: leaveForm.value.reason,
			applyStatus: 0,
			applyTime: new Date().toISOString(),
		};

		const res = await axios.post("/userLeave/insertLeaveApply", submitData);
		// 兼容后端不同返回结构
		const success = (res && res.data && res.data.code === 200) || (res && res.code === 200) || (res && res.status === 200);
		if (success) {
			ElMessage.success("请假申请提交成功，等待审批");
			resetForm();
		} else {
			ElMessage.error(res.data?.message || res?.message || "提交失败");
		}
	} catch (error) {
		console.error("提交请假失败：", error);
		if (error.response?.status === 401) {
			ElMessageBox.confirm("登录已过期，请重新登录", "提示", {
				confirmButtonText: "重新登录",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				localStorage.removeItem("token");
				localStorage.removeItem("isLogin");
				window.location.href = "/login";
			});
		} else {
			ElMessage.error(error.response?.data?.message || "服务器错误，请稍后重试");
		}
	} finally {
		submitLoading.value = false;
	}
};

const resetForm = () => {
	if (formRef.value) formRef.value.resetFields();
	leaveForm.value.leaveDays = 0;
};
</script>

<style scoped>
.leave-apply-container {
	padding: 20px;
	background-color: #f5f7fa;
	min-height: 100%;
}

.leave-apply-card {
	background: white;
	border-radius: 8px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	padding: 24px;
	max-width: 800px;
	margin: 0 auto;
}

.form-title {
	text-align: center;
	color: #303133;
	margin-bottom: 24px;
	font-size: 20px;
	font-weight: 600;
}

.leave-form {
	padding: 0 10px;
}

.el-form-item {
	margin-bottom: 18px;
}

:deep(.el-form-item__label) {
	font-weight: 500;
	color: #606266;
}

.form-actions {
	text-align: center;
	margin-top: 30px;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
	border-radius: 4px;
}

:deep(.el-select) {
	width: 100%;
}
</style>
